import { Request, Response } from 'express';
import { ResponseUtil } from '../utils/response';
import { UploadUtil } from '../utils/upload.util';
import type { AuthenticatedRequest } from '../types/upload';
import { docTypes } from '../constant/upload';

export class UploadController {
  private static instance: UploadController;
  private uploadUtil: UploadUtil;

  private constructor() {
    this.uploadUtil = UploadUtil.getInstance();
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): UploadController {
    if (!UploadController.instance) {
      UploadController.instance = new UploadController();
    }
    return UploadController.instance;
  }

  /**
   * 处理上传的文件
   */
  private handleUploadedFiles(req: AuthenticatedRequest): Express.Multer.File[] {
    if (!req.files) {
      return [];
    }
    
    // 处理文件数组格式
    if (Array.isArray(req.files)) {
      return req.files;
    }
    
    // 处理对象格式 { [fieldname]: File[] }
    const files: Express.Multer.File[] = [];
    Object.keys(req.files).forEach(key => {
      if (Array.isArray(req.files) || !req.files) return;
      const fieldFiles = req.files[key];
      if (Array.isArray(fieldFiles)) {
        files.push(...fieldFiles);
      }
    });
    
    return files;
  }

  /**
   * 上传图片处理
   */
  public uploadImage = async (req: Request, res: Response) => {
    try {
      // 创建multer中间件
      const upload = this.uploadUtil.getUploadMiddleware('image', 5);

      // 使用Promise包装multer中间件
      const uploadPromise = new Promise<void>((resolve, reject) => {
        upload(req, res, (err: any) => {
          if (err) {
            reject(err);
            return;
          }
          resolve();
        });
      });

      // 等待上传完成
      await uploadPromise;
      
      // 处理上传的文件
      const authReq = req as AuthenticatedRequest;
      const files = this.handleUploadedFiles(authReq);

      if (files.length === 0) {
        return ResponseUtil.error(res, '请选择要上传的图片');
      }
      
      // 检查并只保留图片类型文件
      const imageFiles = files.filter(file => {
        return file.mimetype && file.mimetype.startsWith('image/');
      });
      
      if (imageFiles.length === 0) {
        return ResponseUtil.error(res, '请上传有效的图片文件');
      }
      
      // 格式化响应
      const filesInfo = this.uploadUtil.formatResponse(imageFiles);
      return ResponseUtil.success(res, filesInfo, '图片上传成功');
    } catch (error: any) {
      // 只返回错误消息，不输出堆栈跟踪
      return ResponseUtil.error(res, error.message || '上传图片失败');
    }
  };

  /**
   * 上传视频处理
   */
  public uploadVideo = async (req: Request, res: Response) => {
    try {
      // 创建multer中间件
      const upload = this.uploadUtil.getUploadMiddleware('video', 1);

      // 使用Promise包装multer中间件
      const uploadPromise = new Promise<void>((resolve, reject) => {
        upload(req, res, (err: any) => {
          if (err) {
            reject(err);
            return;
          }
          resolve();
        });
      });

      // 等待上传完成
      await uploadPromise;
      
      // 处理上传的文件
      const authReq = req as AuthenticatedRequest;
      const files = this.handleUploadedFiles(authReq);
      
      if (files.length === 0) {
        return ResponseUtil.error(res, '请选择要上传的视频');
      }
      
      // 检查并只保留视频类型文件
      const videoFiles = files.filter(file => {
        return file.mimetype && file.mimetype.startsWith('video/');
      });
      
      if (videoFiles.length === 0) {
        return ResponseUtil.error(res, '请上传有效的视频文件');
      }
      
      // 格式化响应
      const filesInfo = this.uploadUtil.formatResponse(videoFiles);
      return ResponseUtil.success(res, filesInfo, '视频上传成功');
    } catch (error: any) {
      // 只返回错误消息，不输出堆栈跟踪
      return ResponseUtil.error(res, error.message || '上传视频失败');
    }
  };

  /**
   * 上传文档处理
   */
  public uploadDocument = async (req: Request, res: Response) => {
    try {
      // 创建multer中间件
      const upload = this.uploadUtil.getUploadMiddleware('document', 3);

      // 使用Promise包装multer中间件
      const uploadPromise = new Promise<void>((resolve, reject) => {
        upload(req, res, (err: any) => {
          if (err) {
            reject(err);
            return;
          }
          resolve();
        });
      });

      // 等待上传完成
      await uploadPromise;
      
      // 处理上传的文件
      const authReq = req as AuthenticatedRequest;
      const files = this.handleUploadedFiles(authReq);
      
      if (files.length === 0) {
        return ResponseUtil.error(res, '请选择要上传的文档');
      }
      
      // 检查并只保留文档类型文件
      const docFiles = files.filter(file => {
        return file.mimetype && Object.keys(docTypes).includes(file.mimetype)
      });
      
      if (docFiles.length === 0) {
        return ResponseUtil.error(res, '请上传有效的文档文件');
      }
      
      // 格式化响应
      const filesInfo = this.uploadUtil.formatResponse(docFiles);
      return ResponseUtil.success(res, filesInfo, '文档上传成功');
    } catch (error: any) {
      // 只返回错误消息，不输出堆栈跟踪
      return ResponseUtil.error(res, error.message || '上传文档失败');
    }
  };
} 